package org.pr.ddddesigner.infrastructure.helper;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Chenbin
 */
@Component
public class SpringContext implements ApplicationContextAware, BeanFactoryAware {
    private static volatile ApplicationContext ctx;
    private static volatile DefaultListableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        if (ctx == null) {
            synchronized (SpringContext.class) {
                if (ctx == null) {
                    SpringContext.ctx = applicationContext;
                }
            }
        }
    }

    @Override
    public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException {
        if (SpringContext.beanFactory == null) {
            synchronized (SpringContext.class) {
                if (SpringContext.beanFactory == null && beanFactory instanceof DefaultListableBeanFactory) {
                    SpringContext.beanFactory = (DefaultListableBeanFactory) beanFactory;
                }
            }
        }
    }

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    public static boolean containsBean(String name) {
        return ctx.containsBean(name);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return ctx.getBean(name, requiredType);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return ctx.getBean(requiredType);
    }

    public static <T> List<T> getBeans(Class<T> requiredType) {
        return ctx.getBeanProvider(requiredType)
                .stream()
                .collect(Collectors.toList());
    }

    public static void registerSingleton(String beanName, Object singletonObject) {
        beanFactory.registerSingleton(beanName, singletonObject);
    }

    public static void destroySingleton(String beanName) {
        beanFactory.destroySingleton(beanName);
    }
}
